package org.se.scut.pinterest.mina.codec.filte.coder.encoder;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
import org.se.scut.pinterest.mina.codec.msg.PictureUploadMessage;

public class PictureUploadMessageEncoder implements
		MessageEncoder<PictureUploadMessage> {

	private static final String delimiter = "\n";
	private static final CharsetEncoder ENCODER = Charset.forName("UTF-8").newEncoder();
	
	@Override
	public void encode(IoSession arg0, PictureUploadMessage msg,
			ProtocolEncoderOutput out) throws Exception {
		
		IoBuffer buffer = IoBuffer.allocate(msg.getFileLength() + 100).setAutoExpand(true);
		buffer.putString(msg.getSymbol() + delimiter, ENCODER );
		buffer.putString(msg.getFileName() + delimiter, ENCODER);
		buffer.putString(msg.getOverView() + delimiter, ENCODER);
		buffer.putString(msg.getUserID() + delimiter, ENCODER);
		buffer.putString(msg.getPictureTypeID() + delimiter, ENCODER);
		buffer.putString(msg.getAblumID() + delimiter, ENCODER);
		buffer.putString(msg.getFileLength() + delimiter, ENCODER);
		buffer.put(msg.getContent());
		buffer.flip();
		out.write(buffer);
		
	}

}
